<?php

namespace Managers;

class Menu extends BaseManager
{

    protected $_entity = '\Catalog\Menu';
    private $_cacheTime = 1800; // 60 * 30

    /**
     * QB для grid.
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function qb()
    {

        $res = $this->_em->getRepository($this->_entity)->createQueryBuilder('m');

        return $res;

    }

    /**
     * Возвращает меню.
     * @param string $locale
     * @param int $parent
     * @return array|
     */
    public function all($locale = 'en', $parent = 0)
    {
        $cacheName = 'menu_' . $locale . '_' . $parent;
        $res = $this->_getCacheManager()->load($cacheName);
        
        if (!$res) {

            $res = $this->_em->createQueryBuilder()
                    ->select('m', 'p')
                    ->from($this->_entity, 'm')
                    ->join('m.page', 'p')
                    ->where('m.parent = :parent')
                    ->setParameter('parent', $parent)
                    ->orderBy('p.name')
                    ->getQuery()
                    ->getArrayResult();

            $pagesManager = new Pages();
            foreach ($res as $iter => $value) {

                $res[$iter]['translation'] = $pagesManager->shortOneTranslation($locale, $value['page']['id']);
                $res[$iter]['children'] = $this->all($locale, $value['id']);
            }

            $this->_getCacheManager()->save($res, $cacheName, array('menu', $locale), $this->_cacheTime);
        }

        return $res;
    }


}
